package com.manage.platform.excel;

import com.manage.platform.exception.CommonException;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * YWD
 * 2025/11/18
 */
@AllArgsConstructor
@Service
public class ExcelServiceImpl {

    public ResponseEntity<Resource> getUserTemplate(String name) {
        try {
            final String EXCEL_FOLDER_PATH = "./excel";
            final String FILE_NAME = name + ".xlsx";
            // 构建文件路径
            Path filePath = Paths.get(EXCEL_FOLDER_PATH, FILE_NAME).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            // 检查文件是否存在
            if (!resource.exists()) {
                throw new CommonException("文件不存在");
            }
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + FILE_NAME + "\"");
            headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
            headers.add(HttpHeaders.PRAGMA, "no-cache");
            headers.add(HttpHeaders.EXPIRES, "0");
            // 确定Content-Type
            String contentType = determineContentType(FILE_NAME);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } catch (Exception e) {
            throw new CommonException("下载文件失败");
        }
    }

    /**
     * 根据文件名确定Content-Type
     */
    private String determineContentType(String fileName) {
        String extension = getFileExtension(fileName).toLowerCase();
        switch (extension) {
            case "xlsx":
            case "xls":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "txt":
                return "text/plain";
            case "csv":
                return "text/csv";
            default:
                return "application/octet-stream";
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex + 1) : "";
    }



}
